package com.gpframework.module.controller.wages;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.wages.domain.GzAttendanceManagement;
import com.gpframework.module.wages.domain.GzPersonnelFoundation;
import com.gpframework.module.wages.domain.GzWarehouseEvaluation;
import com.gpframework.module.wages.domain.req.GzGenerateReq;
import com.gpframework.module.wages.domain.req.GzWarehouseEvaluationAdd;
import com.gpframework.module.wages.domain.req.GzWarehouseEvaluationReq;
import com.gpframework.module.wages.domain.req.GzWarehouseEvaluationUpdate;
import com.gpframework.module.wages.domain.vo.GzWarehouseEvaluationExcel;
import com.gpframework.module.wages.domain.vo.GzWarehouseEvaluationVo;
import com.gpframework.module.wages.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * @ClassName GzWarehouseEvaluationController
 * @Author gpframework
 * @Date 2024-01-19
 * @Version 1.0.0
 * @Description 仓库评定Controller
 */
@Validated
@Api(tags = "仓库评定")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/wages/warehouseevaluation" )
public class GzWarehouseEvaluationController extends BaseController {

    private final IGzWarehouseEvaluationService iGzWarehouseEvaluationService;

    private final IGzPersonnelFoundationService iGzPersonnelFoundationService;

    private final IGzMonthlyLeaveService iGzMonthlyLeaveService;

    private final IGzTotalSalesItemsService iGzTotalSalesItemsService;

    private final IGzAttendanceManagementService iGzAttendanceManagementService;

    private final IGzWarehousePersonnelService iGzWarehousePersonnelService;
    private final  IGzWarehouseWorkerSalaryLevelService iGzWarehouseWorkerSalaryLevelService;



 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2024-01-19
  * @Param gzWarehouseEvaluation
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:list')")
    @GetMapping("/list")
    public TableDataInfo<GzWarehouseEvaluationVo> list(GzWarehouseEvaluationReq gzWarehouseEvaluationReq)
    {
        startPage();
        QueryWrapper<GzWarehouseEvaluation> lqw = new QueryWrapper<GzWarehouseEvaluation>();
        gzWarehouseEvaluationReq.generatorQuery(lqw,true);
        List<GzWarehouseEvaluationVo> list = iGzWarehouseEvaluationService.listVo(lqw);
        return getDataTable(list);
    }


    @ApiOperation("仓库汇总")
    @PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:list')")
    @GetMapping("/listed")
    public TableDataInfo<GzWarehouseEvaluationVo> listed(GzWarehouseEvaluationReq gzWarehouseEvaluationReq)
    {
        startPage();
        QueryWrapper<GzWarehouseEvaluation> lqw = new QueryWrapper<GzWarehouseEvaluation>();
        gzWarehouseEvaluationReq.generatorQuery(lqw,true);
        List<GzWarehouseEvaluationVo> list = iGzWarehouseEvaluationService.listVoed(lqw);
        return getDataTable(list);
    }


    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzWarehouseEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:add')" )
    @Log(title = "添加仓库评定" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GzWarehouseEvaluationAdd gzWarehouseEvaluationAdd) {
        GzWarehouseEvaluation gzWarehouseEvaluation = Convert.convert(new TypeReference<GzWarehouseEvaluation>() {}, gzWarehouseEvaluationAdd);

        return toAjax(iGzWarehouseEvaluationService.save(gzWarehouseEvaluation) ? 1 : 0);
    }

    @ApiOperation("生成仓库评定")
    //@PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:generateWarehouse')" )
    @PostMapping("/generateWarehouse")
    public AjaxResult generateWarehouse(@RequestBody GzGenerateReq gzGenerateReq) throws ParseException {
        //仓库人员
        List<GzPersonnelFoundation> gzPersonnelFoundations=iGzPersonnelFoundationService.lambdaQuery().eq(GzPersonnelFoundation::getDepartmentType,3).list();
        //删除原有数据
        iGzWarehouseEvaluationService.deleteByMonth(gzGenerateReq.getYearMonth());

        //生成仓库评定
        List<GzWarehouseEvaluation> gzWarehouseEvaluations=new ArrayList<>();
        for (GzPersonnelFoundation gzPersonnelFoundation : gzPersonnelFoundations){
            GzWarehouseEvaluation gzWarehouseEvaluation=new GzWarehouseEvaluation();
            gzWarehouseEvaluation.setMonth(gzGenerateReq.getYearMonth());
            gzWarehouseEvaluation.setDepartmentName(gzPersonnelFoundation.getDepartmentName());
            gzWarehouseEvaluation.setUserId(gzPersonnelFoundation.getId());
            gzWarehouseEvaluation.setName(gzPersonnelFoundation.getName());
            gzWarehouseEvaluation.setPayScale(gzPersonnelFoundation.getSalaryLevel());
            //获取对应的仓库工资等级
            //GzWarehouseWorkerSalaryLevel categoryLevel = iGzWarehouseWorkerSalaryLevelService.getOne(new QueryWrapper<GzWarehouseWorkerSalaryLevel>().eq("category_level", gzPersonnelFoundation.getSalaryLevel()));
            gzWarehouseEvaluation.setPerformanceCoefficient(gzPersonnelFoundation.getPerformanceCoefficient());

            //计算当月按天数绩效
            GzAttendanceManagement gzAttendanceManagement = iGzAttendanceManagementService.getOne(new QueryWrapper<GzAttendanceManagement>().eq("user_id", gzWarehouseEvaluation.getUserId()).eq("month",gzGenerateReq.getYearMonth()));
            if(gzAttendanceManagement ==null || gzAttendanceManagement.getAttendanceDays()==null ){
                throw new BaseException("请在考勤管理输入出勤天数");
            }
            BigDecimal monthlyPerformanceByDays = BigDecimal.valueOf(gzPersonnelFoundation.getPerformanceCoefficient()).multiply(BigDecimal.valueOf(gzAttendanceManagement.getAttendanceDays())).divide(BigDecimal.valueOf(gzAttendanceManagement.getRequireDateNdancedays()), 2, RoundingMode.HALF_UP);
            gzWarehouseEvaluation.setMonthlyPerformanceByDays(monthlyPerformanceByDays.doubleValue());

            /** 评定标准奖金 */
            gzWarehouseEvaluation.setEvaluationCriteriaBonus(gzPersonnelFoundation.getEvaluationCriteriaBonus());



            gzWarehouseEvaluations.add(gzWarehouseEvaluation);
        }
        iGzWarehouseEvaluationService.saveBatch(gzWarehouseEvaluations);
        return AjaxResult.success();
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzWarehouseEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:edit')" )
    @Log(title = "修改仓库评定" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody List<GzWarehouseEvaluationUpdate> list) {
        return toAjax(iGzWarehouseEvaluationService.editBatch(list) ? 1 : 0);
    }


    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzWarehouseEvaluation
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:export')" )
    @Log(title = "导出仓库评定" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GzWarehouseEvaluationReq gzWarehouseEvaluationReq) {
        QueryWrapper<GzWarehouseEvaluation> lqw = new QueryWrapper<GzWarehouseEvaluation>();
        gzWarehouseEvaluationReq.generatorQuery(lqw,true);
        List<GzWarehouseEvaluationVo> list = iGzWarehouseEvaluationService.listVo(lqw);
        ExcelUtil<GzWarehouseEvaluationVo> util = new ExcelUtil<GzWarehouseEvaluationVo>(GzWarehouseEvaluationVo. class);
        return util.exportExcel(list, "warehouseevaluation" );
    }

    @ApiOperation("导出仓库评定模板")
    @Log(title = "导出仓库评定模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate" )
    public AjaxResult exportTemplate() {
        ExcelUtil<GzWarehouseEvaluationExcel> util = new ExcelUtil<>(GzWarehouseEvaluationExcel.class);
        return util.exportExcel(GzWarehouseEvaluationExcel.list(), "仓库评定模板");
    }

    @ApiOperation("导入仓库评定有提示")
    //@PreAuthorize("@ss.hasPermi('wages:attendancemanagement:importList')" )
    @Log(title = "导入仓库评定有提示" , businessType = BusinessType.INSERT)
    @PostMapping("/import")
    public AjaxResult importListNote(MultipartFile file, boolean updateSupport) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }

        // 导入新数据
        ExcelUtil<GzWarehouseEvaluationVo> util = new ExcelUtil<GzWarehouseEvaluationVo>(GzWarehouseEvaluationVo.class);
        List<GzWarehouseEvaluationVo> excelList = util.importCacheExcel(file.getInputStream());

        String message = iGzWarehouseEvaluationService.importListNote(excelList, updateSupport);
        return AjaxResult.success(message);
    }



    @ApiOperation("导入仓库评定")
    //@PreAuthorize("@ss.hasPermi('wages:attendancemanagement:importList')" )
    @Log(title = "导入仓库评定" , businessType = BusinessType.INSERT)
    //@PostMapping("/import")
    public AjaxResult importList(MultipartFile file) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }

        // 导入新数据
        ExcelUtil<GzWarehouseEvaluationExcel> util = new ExcelUtil<>(GzWarehouseEvaluationExcel.class);
        List<GzWarehouseEvaluationExcel> excelList = util.importCacheExcel(file.getInputStream());
        List<GzWarehouseEvaluation> list = Convert.convert(new TypeReference<List<GzWarehouseEvaluation>>() {}, excelList);
        for (GzWarehouseEvaluation gzWarehouseEvaluation : list) {
            if (gzWarehouseEvaluation.getEvaluationCriteriaBonus().equals("0")){
                gzWarehouseEvaluation.setMonthlyEvaluationBonus(BigDecimal.ZERO);
            }else {
                String[] split = gzWarehouseEvaluation.getEvaluationCriteriaBonus().split("-");
                BigDecimal monthlyEvaluationBonus = new BigDecimal(split[1]);
                //计算月度评定奖金 =经理评定 *标准金额
                if (gzWarehouseEvaluation.getManagerEvaluation().compareTo(BigDecimal.ONE)>0){
                    throw new BaseException("经理评定不能大于1");
                }
                gzWarehouseEvaluation.setMonthlyEvaluationBonus(monthlyEvaluationBonus.multiply(gzWarehouseEvaluation.getManagerEvaluation()));
            }

        }

        for (int i = 0; i < list.size(); i++) {
            GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                    .eq("name", list.get(i).getName())
                    .eq("department_name", list.get(i).getDepartmentName())
                    .eq("del_status", YesNoEnum.NO.getKey()));


            GzWarehouseEvaluation gzWarehouseEvaluation = iGzWarehouseEvaluationService.getOne(new QueryWrapper<GzWarehouseEvaluation>()
                    .eq("name", list.get(i).getName())
                    .eq("department_name", list.get(i).getDepartmentName())
                    .eq("month", list.get(i).getMonth())
                    .eq("del_status", YesNoEnum.NO.getKey()));
            if (!StringUtils.isEmpty(gzWarehouseEvaluation))
            {
                list.get(i).setId(gzWarehouseEvaluation.getId());
            }

            list.get(i).setUserId(gzPersonnelFoundation.getId());
        }

        return iGzWarehouseEvaluationService.saveOrUpdateBatch(list) ? AjaxResult.success("导入成功") : AjaxResult.error();
    }



    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzWarehouseEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GzWarehouseEvaluationVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGzWarehouseEvaluationService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzWarehouseEvaluation
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('wages:warehouseevaluation:remove')" )
    @Log(title = "删除仓库评定" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGzWarehouseEvaluationService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }




}
